package com.biz.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import com.framework.entity.Global;
import com.framework.util.Const;
import com.framework.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 统一认证
 * 
 * @author lzq
 *
 */
public class BSIUtil
{
	private static Logger logger = LoggerFactory.getLogger(BSIUtil.class);

	/**
	 * 获取toGetSessionKey
	 * 
	 * @return
	 */
	public static String getSessionKey()
	{
		String newSessionKey = "";
		String getSessionKey = Tools.readTxtFile(Global.SESSION_KEY);
		if ("".equals(getSessionKey))
		{
			logger.debug("################################################");
			logger.debug("载入SessionKey已超时，重新载入");
			logger.debug("################################################");
			newSessionKey = reloadSessionKey();
		}
		else
		{
			String[] accessTokenArg = getSessionKey.split(",");
			long nowTime = new Date().getTime();
			long putTime = Long.parseLong(accessTokenArg[1]);
			long diffTime = Long.parseLong(accessTokenArg[2]);
			if (Math.abs(nowTime - putTime) >= diffTime)
			{
				logger.debug("################################################");
				logger.debug("载入token已超时，重新载入");
				logger.debug("################################################");
				newSessionKey = reloadSessionKey();
			} else
			{
				newSessionKey = accessTokenArg[0];
			}
		}
		return newSessionKey;
	}

	/**
	 * 重新装载AccessToken
	 * 
	 * @return
	 */
	public static String reloadSessionKey()
	{
		String url = Global.GET_SEESION_KEY_URL;
		/***************拼接参数*********************/
		Map<String, String> map = new HashMap<String, String>();
		map.put("loginName", Global.LOGIN_NAME);
		map.put("pwd", Global.PWD);
		map.put("platform", Global.PLATFORM);	
		String x = URLConectionUtil.httpURLConnectionPostDiy(url, map);
		String sessionKey = "";
		JSONObject jobj = JSONObject.fromObject(x);
		
		if("success".equals(jobj.get("flag")))
		{
			sessionKey = jobj.get("sessionKey").toString();
			Tools.writeFile(Global.SESSION_KEY, sessionKey + ","
					+ new Date().getTime() + "," + String.valueOf(25920000000l));
		}else{
			sessionKey = Tools.readTxtFile(Global.SESSION_KEY);
		}
		
		return sessionKey;
	}

	
	
}
